//
//  ForumViewController.m
//  IT爱好者
//
//  Created by dllo on 15/10/16.
//  Copyright © 2015年 Fan. All rights reserved.
//

#import "ForumViewController.h"
#import "Header.h"
#import "CFNetworkFromAFNetworking.h"
#import "ForumTableViewCell.h"
#import "ForumArticleModel.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "FavoriteWapPage.h"
#import "CFWebViewController.h"
#import "HotArticleModel.h"
//#import "UMSocial.h"
#pragma mark 第三页 版块
@interface ForumViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, retain)UISegmentedControl *segmentedControl;
@property(nonatomic, retain)NSMutableArray *dataSourceArray;
@property(nonatomic, retain)NSMutableArray *NewWrightArray;
@property(nonatomic, retain)NSMutableArray *essentialArray;

@property(nonatomic, assign)NSInteger page;
@property(nonatomic, assign)NSInteger totlePage;
@property(nonatomic, retain)NSString *flag;//点击的是哪个segment 做标记并拼接网址

@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)MBProgressHUD *HUD;
@property(nonatomic, assign)BOOL isEnd;
@end

@implementation ForumViewController


-(void)loadView
{
    [super loadView];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.title = _RListM.name;
    _page = 1;
    _totlePage = 1;
    _flag = @"lastdate";
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"share"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(shareAction)];
    self.navigationController.navigationBar.translucent = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSourceArray = [NSMutableArray array];
    
#pragma mark 菊花
    _HUD = [[MBProgressHUD alloc] initWithView:self.view];
    _HUD.labelText = @"正在刷新";
    //    _HUD.detailsLabelText = @"请耐心等待!";
    [_HUD setMode:MBProgressHUDModeIndeterminate];
    [_HUD show:YES];
    _HUD.backgroundColor = [UIColor clearColor];
    
    [self getDataSourceArray];
    self.view.backgroundColor = BackgroundColor;
    
    //判断 是否需要建segment
    if ([_RListM.param allKeys].count == 2) {
        NSArray *SItemsArray = @[@"新回复", @"新发帖", @"精华"];
        _segmentedControl = [[UISegmentedControl alloc]initWithItems:SItemsArray];
        _segmentedControl.frame = CGRectMake(0, 0, 210 * FitWidth, 30 * FitHeight);
        _segmentedControl.tintColor = [UIColor whiteColor];
        _segmentedControl.selectedSegmentIndex = 0;
        [_segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
        
        self.navigationItem.titleView = _segmentedControl;
    }
    
#pragma mark 建一个tableView 显示内容
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - (64) * FitHeight) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.backgroundColor = BackgroundColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_tableView];

    
#pragma mark MJ 刷新
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self getDataSourceArray];
    }];
    
    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getDataSourceArray];
        
    }];
    
    
    [self.view addSubview:_HUD];
    //夜间模式的监听者
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(colorChange) name:@"colorChange" object:nil];
}
#pragma mark - 夜间模式 监听到变化后采取的措施
- (void )colorChange
{
    self.view.backgroundColor = BackgroundColor;
    _tableView.backgroundColor = BackgroundColor;
    [_tableView reloadData];
}

#pragma mark 设置tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger Hempty = (15 + 10 + 15 + 10) * FitHeight;
    //自适应高度
    NSDictionary *dicTitle = [NSDictionary dictionaryWithObjectsAndKeys:contentTextSize, NSFontAttributeName, nil];
    CGRect recttitle = [[self.dataSourceArray[indexPath.row] title] boundingRectWithSize:CGSizeMake(ScreenWidth - 50 * FitWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dicTitle context:nil];
    
    NSInteger Hword = recttitle.size.height + (20 + 10) * FitHeight;
    NSInteger HpicImage = 80 * FitHeight;
    //判断数据是否有图片
    NSInteger n = 0;
    for (NSString *str in [self.dataSourceArray[indexPath.row] pic_url]) {
        if (![str isEqualToString:@""]) {
            n ++;
        }
    }
    if (n >= 1) {
        //有图 返回高度加图的高度
        return Hempty + Hword + HpicImage;
    }else return Hempty + Hword;
    //return 50;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    ForumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[ForumTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.ForumAModel = _dataSourceArray[indexPath.row];
    return cell;
}

#pragma mark 点击 跳到web页
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_tableView deselectRowAtIndexPath:indexPath animated:NO];
    CFWebViewController *CFWVC = [[CFWebViewController alloc]init];
    HotArticleModel *hotAM = _dataSourceArray[indexPath.row];
    NSString *urlString = [NSString stringWithFormat:@"http://lib.wap.zol.com.cn/bbs/ios/detail.php?bbs=%@&bbsid=&boardid=%@&bookid=%@&type=0&page=1&picOpen=1&fontSize=middle&fromType=&vs=430&ssid=(null)", hotAM.bbs, hotAM.boardid, hotAM.bookid];
    FavoriteWapPage *faWapPage = [[FavoriteWapPage alloc]init];
    faWapPage.wapUrlString = urlString;
    faWapPage.title = hotAM.title;
    CFWVC.favorWap = faWapPage;
    [self.navigationController pushViewController:CFWVC animated:YES];
}

#pragma mark 获取数据
- (void)getDataSourceArray
{
    NSString *urlString = [NSString string];
    if ([_RListM.param allKeys].count == 1) {
        //点击的是每日精选
        urlString = [NSString stringWithFormat:@"http://lib.wap.zol.com.cn/bbs/ios/getJingxuan.php?bbs=%@&page=%ld&vs=430", [_RListM.param objectForKey:@"bbs"], _page];
        if (_page <= _totlePage) {
            [CFNetworkFromAFNetworking askObjectByURLString:urlString BodyString:nil WithObjectBlock:^(id object) {
                self.totlePage = [[object objectForKey:@"total"]integerValue];
                NSArray *array = [object objectForKey:@"list"];
                if (_page == 1) {
                    self.dataSourceArray = [NSMutableArray array];
                }
                for (NSDictionary *dic in array) {
                    ForumArticleModel *forumAM = [[ForumArticleModel alloc]init];
                    [forumAM setValuesForKeysWithDictionary:dic];
                    forumAM.bbs = [_RListM.param objectForKey:@"bbs"];
                    [self.dataSourceArray addObject:forumAM];
                }
                [_tableView reloadData];
                [_tableView.header endRefreshing];
                [_tableView.footer endRefreshing];
                _HUD.hidden = YES;
        }];
        }else{
            [_tableView.footer noticeNoMoreData];
        }
        
    }else{
        urlString = [NSString stringWithFormat:@"http://lib.wap.zol.com.cn/bbs/ios/list.php?bbs=%@&boardid=%@&manuid=0&order=%@&page=%ld&productid=0&vs=430", [_RListM.param objectForKey:@"bbs"], [_RListM.param objectForKey:@"boardid"], _flag, _page];
        if (_page <= _totlePage) {
            [CFNetworkFromAFNetworking askObjectByURLString:urlString BodyString:nil WithObjectBlock:^(id object) {
                self.totlePage = [[[object objectForKey:@"list"] objectForKey:@"totalPage"] integerValue];
                NSArray *array = [[object objectForKey:@"list"] objectForKey:@"bookList"];
                if (_page == 1) {
                    self.dataSourceArray = [NSMutableArray array];
                    [_tableView reloadData];
                }
                for (NSDictionary *dic in array) {
                    ForumArticleModel *forumAM = [[ForumArticleModel alloc]init];
                    [forumAM setValuesForKeysWithDictionary:dic];
                    forumAM.bbs = [_RListM.param objectForKey:@"bbs"];
                    forumAM.boardid = [_RListM.param objectForKey:@"boardid"];
                    [self.dataSourceArray addObject:forumAM];
                }
                [_tableView reloadData];
                [_tableView.header endRefreshing];
                [_tableView.footer endRefreshing];
                _HUD.hidden = YES;
            }];
        }else{
            [_tableView.footer noticeNoMoreData];
        }
    }
}

#pragma mark segment的点击事件
- (void)segmentAction:(UISegmentedControl *)sender;
{
    ////NSLog(@"%ld", sender.selectedSegmentIndex);
    switch (sender.selectedSegmentIndex) {
        case 0:
            _page = 1;
            _flag = @"lastdate";
            _HUD.hidden = NO;
            [self getDataSourceArray];
            break;
            
        case 1:
            _page = 1;
            _flag = @"wdate";
            _HUD.hidden = NO;
            [self getDataSourceArray];
            break;
            
        case 2:
            _page = 1;
            _flag = @"good";
            _HUD.hidden = NO;
            [self getDataSourceArray];
            break;
            
        default:
            break;
    }
}

#pragma mark - 分享
//- (void)shareAction
//{
//    
//    NSArray *array = @[UMShareToDouban, UMShareToSina, UMShareToQQ, UMShareToQzone];
//    //[UMSocialSnsService presentSnsController:self appKey:@"507fcab25270157b37000010" shareText:nil shareImage:nil shareToSnsNames:array delegate:self];
//    
//    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"507fcab25270157b37000010" shareText:nil shareImage:nil shareToSnsNames:array delegate:self];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
